import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';


declare var form: any;
declare var base: any;

@Component({
    templateUrl: './map.styleInfo.html'
})
export class MapStyleInfoComponent implements OnInit {

    fs: any = null;

    spriteDic: any = null;
    glyphsDic: any = null;
    browserDic: any = null;
    terminalDic: any = null;
    dataSourceDic: any = null;
    dicDataDic: any = null;
    layerDic: any = null;
    dicTypeDic: any = null;
    kernelDic: any = null;
    defDic: any = null;
    dataServeDic: any = null;
    serviceDic: any = null;
    child: any = {};
    index = -1;

    childTwo: any = {};
    oldChildTwo: any = {};
    pEditRow: any = {};

    LayerDatas: any[] = [{}];
    expandDataCache: any[] = [];
    expandAll = false;
    ts: any;

    constructor(public route: ActivatedRoute, private modalService: NzModalService) {
        this.fs = new form.FormSideSimpleService('styles', {
            orderObject: { order: 0 },
            keyField: 'id',
            randomFields: ['id']
        });

        this.fs.loadData(true);
        // 雪碧图文件字典
        this.spriteDic = new form.DictionaryService('p_sprite_directory');
        // 字体文件字典
        this.glyphsDic = new form.DictionaryService('p_glyphs_directory');
        // 浏览器类型字典
        this.browserDic = new form.DictionaryService('d_browser');
        // 终端类型字典
        this.terminalDic = new form.DictionaryService('d_terminal');
        // 数据源类型字典
        this.dataSourceDic = new form.DictionaryService('d_data_source_type');
        // 图层类型字典
        this.layerDic = new form.DictionaryService('d_layer_type');
        // 图层目录字典
        this.dicTypeDic = new form.DictionaryService('d_dictype');
        this.dicTypeDic.loadAll();
        //指标目录
        this.dicDataDic = new form.DictionaryService('indexclummn');
        this.dicDataDic.loadAll();
        // 图层目录字典
        this.kernelDic = new form.DictionaryService('d_kernel');
        this.kernelDic.loadAll();
        // 数据定义
        this.defDic = new form.DictionaryService('g_data_definition');
        this.defDic.loadAll();

        // 数据源服务器类型
        this.dataServeDic = new form.DictionaryService('d_souce_server_type');
        this.dataServeDic.loadAll();

        // 数据源服务器类型
        this.serviceDic = new form.DictionaryService('g_custom_service_config');
        this.serviceDic.loadAll();

        this.ts = new form.TreeService();
    }

    // 初始化执行
    ngOnInit() {
        this.initData();

        // 浏览器关闭监
        window.onbeforeunload = () => {
            // tslint:disable-next-line: deprecation
            const e: any = window.event;
            e.returnValue = ('请确认已保存，是否离开？');
            return e;
        };
    }

    change(item) {
        // 定义对象
        const data = this.serviceDic.datas;
        if (data) {
            data.forEach(e => {
                if (item === e.id && e.other) {
                    const sourceInfo = e.other;
                    this.child.type = sourceInfo.type;
                    this.child.name = sourceInfo.name;
                    this.child.serverType = sourceInfo.serverType;
                    this.child.metedata = sourceInfo.metedata;
                    this.child.propertys = sourceInfo.propertys;
                }
            });
        }
    }

    // 载入数据根据查询Id
    initData() {
        let id = '-1';
        let sid = '';
        this.route.queryParams.subscribe((res) => {
            if (res.id) {
                id = res.id;
            }
            if (res.sid) {
                sid = res.sid;
            }
        });
        this.fs.editRowByKey(id, (item) => {
            this.fs.er.styleId = sid;
            this.LayerDatas = item.layers;
            this.treeflash();
        });
    }

    // 添加数据源子表记录
    addRow() {
        this.fs.openEdit();
        this.child = { id: base.BaseService.getGUID() };
        this.index = -1;
    }

    // 子表详情编辑
    editRow(row?: any, i?: number) {
        if (row == null) {
            return false;
        }

        this.fs.openEdit();
        this.child = base.BaseService.deepCopy(row);
        this.index = i;
    }

    // 数据源子表弹窗保存
    childSave() {
        if (this.index === -1) {
            this.fs.er.sources.push(this.child);
        } else {
            this.fs.er.sources[this.index] = this.child;
        }
        this.fs.closeEdit();
    }

    // 数据源子表弹窗关闭
    childClose() {
        this.fs.closeEdit();
    }

    // 图层新增
    addLayerRow() {
        this.childTwo = { id: base.BaseService.getGUID(), pid: '0' };
        this.oldChildTwo = null;
        this.pEditRow = null;
        this.childTwoOpen();
    }
    // 图层添加子项
    addLayerChildRow(prow: any) {
        this.childTwo = { id: base.BaseService.getGUID(), pid: prow.id };
        this.oldChildTwo = null;
        this.pEditRow = prow;
        this.childTwoOpen();
    }
    // 图层编辑
    editLayerRow(row?: any) {
        if (row == null) {
            return false;
        }
        this.oldChildTwo = row;
        this.pEditRow = null;

        const parent = row.parent;
        const children = row.children;
        delete row.parent;
        delete row.children;
        const copyRow = base.BaseService.deepCopy(row);
        row.parent = parent;
        row.children = children;

        this.childTwo = copyRow;
        this.childTwoOpen();
    }
    // 图层编辑保存
    childTwoSave() {
        if (this.childTwo.group === '2') {
            this.childTwo.leaf = true;
        } else {
            this.childTwo.leaf = false;
        }

        if (this.oldChildTwo === null) {
            if (this.pEditRow) {
                if (!this.pEditRow.children) {
                    this.pEditRow.children = [];
                }
                this.pEditRow.children.push(this.childTwo);
            } else {
                this.LayerDatas.push(this.childTwo);
            }
            this.treeflash();
        } else {
            base.BaseService.copy(this.childTwo, this.oldChildTwo);
        }
        this.childTwoClose();
    }
    // 删除子表
    delChildTwo(row) {
        const id = row.id;
        let pDatas = [];
        if (row.parent) {
            pDatas = row.parent.children;
        } else {
            pDatas = this.LayerDatas;
        }
        let i = -1;
        for (let j = 0; j < pDatas.length; j++) {
            if (pDatas[j].id === id) {
                i = j;
            }
        }
        if (i !== -1) {
            pDatas.splice(i, 1);
        }
        this.treeflash();
    }

    private treeflash() {
        const data = this.getAll(this.LayerDatas);
        this.oParent(data);
        this.LayerDatas = data;
        this.expandDataCache = this.ts.getExpandData(data, this.expandAll);
    }

    childTwoClose(): void {
        this.fs.isEditVisible2 = false;
    }

    childTwoOpen(): void {
        this.fs.isEditVisible2 = true;
    }

    // 大弹窗保存
    save() {
        const er = this.fs.er;
        if (!er.id) {
            er.id = base.BaseService.getGUID();
        }
        if (!er.name || er.name === ''
            || !er.order || er.order === ''
            || !er.sprite || er.sprite === ''
            || !er.terminal || er.terminal === ''
            || !er.browser || er.browser === '') {
            this.modalService.success({
                nzTitle: '系统提示',
                nzContent: '名称、序号、雪碧图、浏览器、终端必填!'
            });
            return;
        }

        // 保存前处理子表对象
        const list = [];
        if (this.LayerDatas) {
            this.getList(this.LayerDatas, list);
        }
        list.forEach((item: any) => {
            delete item.parent;
            delete item.children;
        });
        er.layers = list;

        this.fs.save(er, (data) => {
            this.modalService.success({
                nzTitle: '系统提示',
                nzContent: '保存成功!'
            });
            this.fs.er = data;
        }, () => {
            this.modalService.error({
                nzTitle: '系统提示',
                nzContent: '保存失败!'
            });
        });
    }

    getList(layers: any[], list: any[]) {
        layers.forEach((item: any) => {
            list.push(item);
            if (item.children) {
                this.getList(item.children, list);
            }
        });
    }

    // 大弹窗关闭
    close() {
        window.close();
    }

    getAll(layserDatas: any) {
        const treeDatas = [];
        if (!layserDatas) {
            return treeDatas;
        }
        const oneLevel = this.getChild(layserDatas, '0');
        if (oneLevel != null && oneLevel.length > 0) {
            if (oneLevel != null && oneLevel.length > 0) {
                oneLevel.forEach(data => {
                    treeDatas.push(data);
                    this.addNext(layserDatas, data);
                });
            }
        }
        return treeDatas;
    }

    getChild(datas: any, pid: string) {
        const resDatas = [];
        datas.forEach(data => {
            if (data.pid === pid) {
                resDatas.push(data);
            }
        });

        // 排序
        resDatas.sort((a: any, b: any) => {
            return b.order - a.order; // 倒序
        });
        return resDatas;
    }

    addNext(layserDatas: any, item: any) {
        const nextLevel = this.getChild(layserDatas, item.id);
        if (nextLevel != null && nextLevel.length > 0) {
            nextLevel.forEach(data => {
                this.addNext(layserDatas, data);
            });
            item.children = nextLevel;
        }
    }

    // 处理数据的parent
    private oParent(data) {
        if (data && data.length > 0) {
            data.forEach(item => {
                this.oParentForChild(item);
            });
        }
    }

    private oParentForChild(data) {
        if (data.children && data.children.length > 0) {
            data.children.forEach(cItem => {
                cItem.parent = data;
                this.oParentForChild(cItem);
            });
        }
    }
}
